<template>
  <div class="checkout">
    <el-card class="checkout-card">
      <div slot="header" class="header">
        <span>确认订单</span>
      </div>
      
      <!-- 收货地址 -->
      <div class="section address-section">
        <h3>收货地址</h3>
        <div v-if="!showAddressForm" class="address-list">
          <div v-if="addresses.length > 0">
            <el-radio-group v-model="selectedAddressId">
              <div v-for="address in addresses" :key="address.id" class="address-item">
                <el-radio :label="address.id">
                  <div class="address-content">
                    <div class="address-info">
                      <span class="name">{{ address.receiverName }}</span>
                      <span class="phone">{{ address.receiverPhone }}</span>
                    </div>
                    <div class="address-detail">
                      {{ address.province + address.city + address.district + address.detailAddress }}
                    </div>
                  </div>
                </el-radio>
              </div>
            </el-radio-group>
          </div>
          <el-button type="text" @click="showAddressForm = true">
            <i class="el-icon-plus"></i> 添加新地址
          </el-button>
        </div>
        
        <!-- 添加/编辑地址表单 -->
        <div v-else class="address-form">
          <el-form :model="addressForm" :rules="addressRules" ref="addressForm" label-width="100px">
            <el-form-item label="收货人" prop="receiverName">
              <el-input v-model="addressForm.receiverName"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="receiverPhone">
              <el-input v-model="addressForm.receiverPhone"></el-input>
            </el-form-item>
            <el-form-item label="所在地区" required>
              <el-cascader
                v-model="addressForm.region"
                :options="regionOptions"
                @change="handleRegionChange">
              </el-cascader>
            </el-form-item>
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input type="textarea" v-model="addressForm.detailAddress"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitAddress">保存地址</el-button>
              <el-button @click="showAddressForm = false">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 商品清单 -->
      <div class="section order-section">
        <h3>商品清单</h3>
        <div class="product-list">
          <div v-for="item in checkoutItems" :key="item.id" class="product-item">
            <img :src="getImageUrl(item.productImage)" :alt="item.productName">
            <div class="product-info">
              <div class="product-name">{{ item.productName }}</div>
              <div class="product-price">¥{{ item.price }}</div>
            </div>
            <div class="product-quantity">x {{ item.quantity }}</div>
            <div class="product-total">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="section payment-section">
        <h3>支付方式</h3>
        <el-radio-group v-model="paymentMethod">
          <el-radio label="alipay">支付宝</el-radio>
          <el-radio label="wechat">微信支付</el-radio>
        </el-radio-group>
      </div>

      <!-- 订单备注 -->
      <div class="section remark-section">
        <h3>订单备注</h3>
        <el-input
          type="textarea"
          v-model="remark"
          placeholder="请输入订单备注（选填）"
          :rows="2">
        </el-input>
      </div>

      <!-- 订单金额 -->
      <div class="section amount-section">
        <div class="amount-item">
          <span>商品总额</span>
          <span>¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <div class="amount-item">
          <span>运费</span>
          <span>¥{{ shippingFee.toFixed(2) }}</span>
        </div>
        <div class="amount-item total">
          <span>实付金额</span>
          <span class="price">¥{{ (totalAmount + shippingFee).toFixed(2) }}</span>
        </div>
      </div>

      <!-- 提交订单 -->
      <div class="submit-section">
        <el-button type="primary" :loading="submitting" @click="submitOrder">
          提交订单
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { createOrder, createOrderFromCart } from '@/api/order'
import { getAddressList, addAddress } from '@/api/user'

export default {
  name: 'Checkout',
  data() {
    return {
      addresses: [],
      selectedAddressId: null,
      showAddressForm: false,
      addressForm: {
        receiverName: '',
        receiverPhone: '',
        region: [],
        detailAddress: '',
        province: '',
        city: '',
        district: ''
      },
      addressRules: {
        receiverName: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        receiverPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      },
      regionOptions: [
        {
          value: '广东省',
          label: '广东省',
          children: [
            {
              value: '广州市',
              label: '广州市',
              children: [
                { value: '天河区', label: '天河区' },
                { value: '海珠区', label: '海珠区' },
                { value: '越秀区', label: '越秀区' }
              ]
            },
            {
              value: '深圳市',
              label: '深圳市',
              children: [
                { value: '南山区', label: '南山区' },
                { value: '福田区', label: '福田区' },
                { value: '罗湖区', label: '罗湖区' }
              ]
            }
          ]
        },
        {
          value: '北京市',
          label: '北京市',
          children: [
            {
              value: '北京市',
              label: '北京市',
              children: [
                { value: '朝阳区', label: '朝阳区' },
                { value: '海淀区', label: '海淀区' },
                { value: '东城区', label: '东城区' }
              ]
            }
          ]
        }
      ],
      paymentMethod: 'alipay',
      remark: '',
      submitting: false,
      shippingFee: 0 // 运费，可以根据实际业务设置
    }
  },
  computed: {
    ...mapState('checkout', ['checkoutItems']),
    totalAmount() {
      return this.checkoutItems.reduce((total, item) => {
        return total + item.price * item.quantity
      }, 0)
    }
  },
  created() {
    this.fetchAddresses()
    // 如果没有结算商品，返回购物车页面
    if (!this.checkoutItems || this.checkoutItems.length === 0) {
      this.$message.warning('请先选择要结算的商品')
      this.$router.push('/main/shop/cart')
    }
  },
  methods: {
    ...mapActions('cart', ['clearCart']),
    
    async fetchAddresses() {
      try {
        const response = await getAddressList()
        if (response.code === 200) {
          this.addresses = response.data
          if (this.addresses.length > 0) {
            this.selectedAddressId = this.addresses[0].id
          }
        }
      } catch (error) {
        this.$message.error('获取地址列表失败')
      }
    },

    handleRegionChange(value) {
      if (value.length === 3) {
        this.addressForm.province = value[0]
        this.addressForm.city = value[1]
        this.addressForm.district = value[2]
      }
    },

    async submitAddress() {
      try {
        await this.$refs.addressForm.validate()
        const response = await addAddress(this.addressForm)
        if (response.code === 200) {
          this.$message.success('添加地址成功')
          this.showAddressForm = false
          await this.fetchAddresses()
        }
      } catch (error) {
        this.$message.error('添加地址失败')
      }
    },

    async submitOrder() {
      if (!this.selectedAddressId) {
        this.$message.warning('请选择收货地址')
        return
      }

      if (!this.paymentMethod) {
        this.$message.warning('请选择支付方式')
        return
      }

      try {
        this.submitting = true
        const orderData = {
          addressId: this.selectedAddressId,
          paymentMethod: this.paymentMethod,
          remark: this.remark,
          items: this.checkoutItems.map(item => ({
            productId: item.productId,
            quantity: item.quantity
          }))
        }

        const response = await createOrderFromCart(orderData)
        if (response.code === 200) {
          this.$message.success('订单创建成功')
          // 清空购物车
          await this.clearCart()
          // 清空结算商品
          this.$store.commit('checkout/CLEAR_CHECKOUT_ITEMS')
          // 跳转到支付页面
          this.$router.push(`/main/shop/payment/${response.data.id}`)
        }
      } catch (error) {
        console.error('创建订单失败:', error)
        this.$message.error('创建订单失败: ' + (error.message || '未知错误'))
      } finally {
        this.submitting = false
      }
    },

    getImageUrl(path) {
      if (!path) {
        return require('@/assets/default.jpg');
      }
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径以 / 开头
      if (!path.startsWith('/')) {
        path = '/' + path;
      }
      
      // 构建完整URL
      return serverUrl + path;
    }
  }
}
</script>

<style lang="scss" scoped>
.checkout {
  padding: 20px;

  .checkout-card {
    .header {
      font-size: 18px;
      font-weight: bold;
    }

    .section {
      margin-bottom: 30px;
      
      h3 {
        margin: 0 0 15px;
        font-size: 16px;
        color: #333;
      }
    }

    .address-section {
      .address-list {
        .address-item {
          margin-bottom: 10px;
          padding: 10px;
          border: 1px solid #eee;
          border-radius: 4px;

          &:hover {
            border-color: #409EFF;
          }

          .address-content {
            margin-left: 5px;

            .address-info {
              .name {
                font-weight: bold;
                margin-right: 10px;
              }
            }

            .address-detail {
              color: #666;
              margin-top: 5px;
            }
          }
        }
      }
    }

    .product-list {
      .product-item {
        display: flex;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #eee;

        img {
          width: 80px;
          height: 80px;
          object-fit: cover;
          margin-right: 15px;
        }

        .product-info {
          flex: 1;

          .product-name {
            font-size: 14px;
            color: #333;
          }

          .product-price {
            color: #f56c6c;
            margin-top: 5px;
          }
        }

        .product-quantity {
          margin: 0 20px;
          color: #666;
        }

        .product-total {
          font-weight: bold;
          color: #f56c6c;
        }
      }
    }

    .amount-section {
      .amount-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;

        &.total {
          border-top: 1px solid #eee;
          padding-top: 10px;
          margin-top: 10px;
          font-weight: bold;

          .price {
            color: #f56c6c;
            font-size: 20px;
          }
        }
      }
    }

    .submit-section {
      text-align: right;
      margin-top: 20px;
    }
  }
}
</style> 